package xian.woniuxy.reghos.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.api.RemoteDeptService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.common.redis.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import xian.woniuxy.customer.dubboService.RemotePatientService;
import xian.woniuxy.domain.Patient;
import xian.woniuxy.reghos.domain.bo.RegisterBo;
import xian.woniuxy.reghos.domain.vo.OperationVo;
import xian.woniuxy.reghos.domain.vo.RegisterVo;
import xian.woniuxy.domain.Register;
import xian.woniuxy.reghos.mapper.RegisterMapper;
import xian.woniuxy.reghos.service.IRegisterService;

import java.time.Duration;
import java.util.*;

/**
 * 挂号Service业务层处理
 *
 * @author ataoxz
 * @date 2022-08-23
 */
@RequiredArgsConstructor
@Service
public class RegisterServiceImpl implements IRegisterService {

    private final RegisterMapper baseMapper;
    @DubboReference
    private final RemoteUserService remoteUserService;
    @DubboReference
    private final RemoteDeptService remoteDeptService;
    @DubboReference
    private final RemotePatientService remotePatientService;


    /**
     * 查询挂号
     */
    @Override
    public RegisterVo queryById(Long registerId){
        return baseMapper.selectVoById(registerId);
    }

    /**
     * 查询挂号列表
     */
    @Override
    public TableDataInfo<RegisterVo> queryPageList(RegisterBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Register> lqw = buildQueryWrapper(bo);
        Page<RegisterVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<SysDept> sysDepts = remoteDeptService.deptList();
        HashMap<Long, String> map = new HashMap<>(16);
        sysDepts.forEach(dept -> {
            map.put(dept.getDeptId(), dept.getDeptName());
        });
        List<RegisterVo> records = result.getRecords();
        records.forEach(registerVo -> {
            registerVo.setDepName(map.get(registerVo.getDepId()));
            Patient patient = remotePatientService.queryById(registerVo.getPatientId());
            registerVo.setPatientName(patient.getPatientName());
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询挂号列表
     */
    @Override
    public List<RegisterVo> queryList(RegisterBo bo) {
        LambdaQueryWrapper<Register> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Register> buildQueryWrapper(RegisterBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Register> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, Register::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), Register::getUserName, bo.getUserName());
        lqw.eq(bo.getRegisterDate() != null, Register::getRegisterDate, bo.getRegisterDate());
        lqw.like(StringUtils.isNotBlank(bo.getDepName()), Register::getDepName, bo.getDepName());
        return lqw;
    }

    /**
     * 新增挂号
     */
    @Override
    public Boolean insertByBo(RegisterBo bo) {
        SysUser user = remoteUserService.queryByUserName(bo.getUserName());
        bo.setUserId(user.getUserId());
        SysDept dept = remoteDeptService.selectByDeptName(bo.getDepName());
        bo.setDepId(dept.getDeptId());
        Register add = BeanUtil.toBean(bo, Register.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setRegisterId(add.getRegisterId());
        }
        return flag;
    }

    /**
     * 修改挂号
     */
    @Override
    public Boolean updateByBo(RegisterBo bo) {
        Register update = BeanUtil.toBean(bo, Register.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Register entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除挂号
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void endReg(Long registerId) {
        Register register =  RedisUtils.getCacheObject("guahaoregister:" + registerId);
        Long patientId = register.getPatientId();
        Patient patient = remotePatientService.queryById(patientId);
        RedisUtils.deleteKeys("guahaoregister:" + registerId);
        RedisUtils.deleteKeys("guahaoexist:"+patient.getPatientCardId());
        RedisUtils.deleteKeys("guahaopatient:"+patient.getPatientCardId());
        List<Register> list = RedisUtils.getCacheList("guahaolist:" + register.getUserId());
        list.removeIf(register1 -> registerId.equals(register1.getRegisterId()));
        RedisUtils.deleteKeys("guahaolist:" + register.getUserId());
        if (!list.isEmpty()) {
            RedisUtils.setCacheList("guahaolist:" + register.getUserId(), list);
            RedisUtils.expire("guahaolist:" + register.getUserId(), Duration.ofHours(5));
        }
        Register register1 = baseMapper.selectById(registerId);
        register1.setRegisterState("1");
        baseMapper.updateById(register1);
    }

    @Override
    public void doGuoHao(Long registerId) {
        Register register = RedisUtils.getCacheObject("guahaoregister:" + registerId);
        List<Register> list = RedisUtils.getCacheList("guahaolist:" + register.getUserId());
        list.removeIf(register1 -> registerId.equals(register1.getRegisterId()));
        list.add(register);
        RedisUtils.deleteKeys("guahaolist:" + register.getUserId());
        RedisUtils.setCacheList("guahaolist:" + register.getUserId(), list);
        RedisUtils.expire("guahaolist:" + register.getUserId(), Duration.ofHours(5));
    }
}
